package com.ssi.myshop.ui.custom;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import com.ssi.myshop.R;

public class AutoLoopViewPager extends ViewPager {

    private static final String TAG = "AutoLoopViewPager";

    public static final long DEFAULT_DURATION = 3000;
    private long mDuration = DEFAULT_DURATION;

    public AutoLoopViewPager(@NonNull Context context) {
        this(context, null);
    }

    public AutoLoopViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.AutoLoopStyle);
        mDuration = ta.getInteger(R.styleable.AutoLoopStyle_duration, (int) DEFAULT_DURATION);
        ta.recycle();
    }

    private boolean isLoop = false;

    public void startLoop() {
        isLoop = true;
        post(mTask);
    }

    private Runnable mTask = new Runnable() {
        @Override
        public void run() {
            int currentItem = getCurrentItem();
            currentItem++;
            setCurrentItem(currentItem);
            if (isLoop) {
                postDelayed(this, mDuration);
            }
        }
    };

    public void stopLoop() {
        removeCallbacks(mTask);
        isLoop = false;
    }
}
